package xyz.chenyongpeng.buyjj.controller;

import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.http.HttpUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.config.WxPayConfig;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.github.binarywang.wxpay.util.SignUtils;
import xyz.chenyongpeng.buyjj.controller.base.GenericController;
import xyz.chenyongpeng.buyjj.entity.MyOrder;
import xyz.chenyongpeng.buyjj.service.IOrderService;
import xyz.chenyongpeng.buyjj.utils.ReturnModel;
import xyz.chenyongpeng.buyjj.utils.XMLUtil;

/**
 * 微信支付Controller
 * <p>
 */
@Controller
@RequestMapping(value = "wxPay")
public class PaymentController extends GenericController {

    @Autowired
    private WxPayConfig payConfig;
    @Autowired
    private WxPayService payService;

    @Autowired
    private IOrderService orderService;

    public static final String WXTZ = "https://www.hcmis.cn";
    public static final String notifyUrl = "";

    /**
     * 返回前台H5调用JS支付所需要的参数，公众号支付调用此接口
     *
     * @param response
     * @param request
     */
    @RequestMapping(value = "getJSSDKPayInfo")
    public void getJSSDKPayInfo(HttpServletResponse response,
                                HttpServletRequest request) {
        ReturnModel returnModel = new ReturnModel();
        WxPayUnifiedOrderRequest prepayInfo = WxPayUnifiedOrderRequest.newBuilder()
                .openid(request.getParameter("openid"))
                .outTradeNo(request.getParameter("out_trade_no"))
                .totalFee(Integer.valueOf(request.getParameter("total_fee")))
                .body(request.getParameter("body"))
                .tradeType(request.getParameter("trade_type"))
                .spbillCreateIp(request.getParameter("spbill_create_ip"))
                .notifyUrl(notifyUrl)
                .build();

        try {
            Map<String, String> payInfo = this.payService.getPayInfo(prepayInfo);
            returnModel.setResult(true);
            returnModel.setDatum(payInfo);
            renderString(response, returnModel);
        } catch (WxPayException e) {
            returnModel.setResult(false);
            returnModel.setReason(e.getErrCodeDes());
            renderString(response, returnModel);
            this.logger.error(e.getErrCodeDes());
        }
    }

    /**
     * 微信通知支付结果的回调地址，notify_url
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "getJSSDKCallbackData")
    public void getJSSDKCallbackData(HttpServletRequest request,
                                     HttpServletResponse response) {
        try {
            synchronized (this) {
                Map<String, String> kvm = XMLUtil.parseRequestXmlToMap(request);
                if (SignUtils.checkSign(kvm, null, this.payConfig.getMchKey())) {
                    if (kvm.get("result_code").equals("SUCCESS")) {
                        // 微信服务器通知此回调接口支付成功后，通知给业务系统做处理
                        MyOrder myOrder = new MyOrder();
                        myOrder.setFlag(2); // 支付成功
                        myOrder.setOrderId(kvm.get("out_trade_no"));
                        orderService.update(myOrder,(Wrapper) new UpdateWrapper<>().eq("order_id", kvm.get("out_trade_no")));

                        // 给乔木数据接口
                        String urlString = WXTZ+"/Api/Order/wxPaySuccess";
                        Map<String, Object> paramMap = new HashMap<>();
                        paramMap.put("order_sn", kvm.get("out_trade_no"));
                        String postresult = HttpUtil.post(urlString, paramMap);

                        logger.info("out_trade_no: " + kvm.get("out_trade_no") + " pay SUCCESS!");
                        response.getWriter().write("<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[ok]]></return_msg></xml>");
                    } else {
                        this.logger.error("out_trade_no: "
                                + kvm.get("out_trade_no") + " result_code is FAIL");
                        response.getWriter().write(
                                "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[result_code is FAIL]]></return_msg></xml>");
                    }
                } else {
                    response.getWriter().write(
                            "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[check signature FAIL]]></return_msg></xml>");
                    this.logger.error("out_trade_no: " + kvm.get("out_trade_no")
                            + " check signature FAIL");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


